<template>
  <div>
    <BasicTable ref="tableRef" @register="registerTable" @fetch-success="onFetchSuccess">
      <template #toolbar>
        <a-button v-if="hasPermission([PermissionEnum.CONNECTION_MANAGE])" type="primary" @click="handleCreate"> 新增互联 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="createActions(record)"
          />
        </template>
      </template>
    </BasicTable>
    <PartnerDetailDrawer @register="registerPartnerDetailDrawer" @success="handleSuccess" />
    <ConnectionDrawer @register="registerConnectionDrawer" @success="handleSuccess" />
    <CertificateDrawer @register="registerCertificateDrawer" @success="handleSuccess" />
    <CertificateDetailDrawer @register="registerCertificateDetailDrawer" @success="handleSuccess" />
    <HistoryModal @register="registerHistoryModal" />
  </div>
</template>
<script lang="tsx" setup>
  import { ref, unref, nextTick } from 'vue'; 
  import { BasicTable, useTable, TableAction, ActionItem } from '@/components/Table';
  import { getConnectionList, uploadCertificate, changeConnectionState } from '@/api/connection';
  import { UpdateConnectionStateParams } from '@/api/model/connection';

  import { useDrawer } from '@/components/Drawer';
  import { useModal } from '@/components/Modal';
  import PartnerDetailDrawer from '@/views/wex/components/PartnerDetailDrawer/index.vue';
  import ConnectionDrawer from './ConnectionDrawer.vue';
  import CertificateDrawer from '../components/CertificateDrawer/index.vue';
  import CertificateDetailDrawer from '../components/CertificateDetailDrawer/index.vue';
  import HistoryModal from './HistoryModal.vue';
  import { searchFormSchema } from './data';

  import { connectionStateEnum, connectionStateMap } from '@/enums/connection'
  import { formatToDate, formatToDateTime } from '@/utils/dateUtil'
  import { Button } from '@/components/Button';
  import { BasicColumn, TableActionType } from '@/components/Table';
  import { SimpleUpload } from '@/components/Upload';
  import { downloadByUrl } from '@/utils/file/download';
  import { usePermission } from '@/hooks/web/usePermission';
  import { PermissionEnum } from '@/enums/permissionEnum'
  import { partnerTypeEnum } from '@/enums/partner';
  import { useRouter } from 'vue-router';

  const router = useRouter();
  const { currentRoute } = router;
  const route = unref(currentRoute);
  const query = route.query;
  const tableRef = ref<Nullable<TableActionType>>(null);
  const ifOpenCertificate = ref(query.thirdparty_app ? true : false);

  const { hasPermission } = usePermission();

  const [registerHistoryModal, { openModal: openHistoryModal }] = useModal();

  const columns: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: ['partner', 'name'],
      width: 150,
      ellipsis: false,
      customRender: ({ record }) => {
        return (
          <Button onClick={() => showPartnerDetail(record)} type="link">
            {() => record.partner.name}
          </Button>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 80,
      customRender: ({ record }) => {
        return connectionStateMap[record.state];
      },
    },
    {
      title: '创建渠道',
      dataIndex: 'thirdparty_app',
      width: 80,
      customRender: ({ record }) => {
        return record.thirdparty_app === null? '自建': record.thirdparty_app.name;
      },
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      width: 100,
      customRender: ({ record }) => {
        if (record.start_time) {
          return formatToDate(record.start_time);
        }
        return '-'
      },
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      width: 100,
      customRender: ({ record }) => {
        if (record.end_time) {
          return formatToDate(record.end_time);
        }
        return '-'
      },
    },
    {
      title: '我方授权书',
      dataIndex: 'our_side_certificate',
      width: 180,
      align: 'left',
      customRender: ({ record }) => {
        const url = record.our_side_certificate?.url;
        const generateText = url ? '更换': '生成';

        const handleViewCertificate = () => {
          viewCertificate(record.our_side_certificate);
        }

        const handleDownload = () => {
          downloadCertificate(record);
        }

        const handleGenerate = () => {
          generateCertificate(record);
        }

        return (
          <div>
            <div style="display:inline-block;">{ url? '已生成': '未生成' }</div>
            <div onClick={handleViewCertificate} hidden={!url} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>查看</span></div>
            <div onClick={handleGenerate} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>{ generateText }</span></div>
            <div onClick={handleDownload} hidden={!url} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>下载</span></div>
          </div>
        )
      },
    },
    {
      title: '对方授权书',
      dataIndex: 'other_side_certificate',
      width: 100,
      align: 'left',
      customRender: ({ record }) => {
        const url = record.other_side_certificate?.url;
        const uploaded_text = url ? '已上传': '未上传';

        const handleViewCertificate = () => {
          viewCertificate(record.other_side_certificate);
        }
        const handleUpload = async (file, onUploadProgress) => {
          const res = await uploadCertificate(record.id, file, onUploadProgress);
          return res;
        };
        const handleChange = () => {
          reload();
        }
        return (
          <div>
            <div style="display:inline-block;">{ uploaded_text }</div>
            <div style="display:inline-block;margin-left:8px">
              <SimpleUpload
                maxSize={5}
                maxNumber={1}
                api={(file, onUploadProgress) => handleUpload(file, onUploadProgress)}
                class="my-5"
                after-close={() => handleChange()}
              />
            </div>
            <div onClick={handleViewCertificate} hidden={!url} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>查看</span></div>
        </div>
        )
      },
    },
    {
      title: '最近更新数据',
      dataIndex: 'latest_pull_data_at',
      width: 120,
      customRender: ({ record }) => {
        if (record.latest_pull_data_at) {
          return formatToDateTime(record.latest_pull_data_at);
        }
        return '-'
      },
    },
    {
        title: '创建时间',
        dataIndex: 'created_at',
        width: 140,
        customRender: ({ record }) => {
          return formatToDateTime(record.created_at);
        },
      },
  ];

  const [registerPartnerDetailDrawer, { openDrawer: openPartnerDetailDrawer }] = useDrawer();
  const [registerCertificateDrawer, { openDrawer: openCertificateDrawer }] = useDrawer();
  const [registerCertificateDetailDrawer, { openDrawer: openCertificateDetailDrawer }] = useDrawer();
  const [registerConnectionDrawer, { openDrawer: openConnectionDrawer }] = useDrawer();

  const searchInfo = {
    type: partnerTypeEnum.ORG,
    thirdparty_app: query.thirdparty_app,
    thirdparty_id: query.thirdparty_id,
  }

  const [registerTable, { reload }] = useTable({
    title: '已互联',
    api: getConnectionList,
    columns,
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchema,
    },
    searchInfo: searchInfo,
    beforeFetch: (info) => {
      if (!!info.state) {
        info.state = info.state.join(',')
      }
      return info;
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
      align: 'center',
    },
  });

  const createActions = (record) => {
    const actions: ActionItem[] = [];
    if (record.state == connectionStateEnum.ONGOING || record.state == connectionStateEnum.DRAFT ) {
      actions.push({
        label: '作废',
        ifShow: hasPermission([PermissionEnum.CONNECTION_MANAGE]),
        color: 'error',
        popConfirm: {
          title: '确认作废？',
          confirm: () => {
            handleCancel(record);
          },
        },
      })
    }
    actions.push({
      label: '查看历史',
      ifShow: hasPermission([PermissionEnum.CONNECTION_VIEW]),
      onClick: () => {
        openHistoryModal(true, {
          record,
        });
      },
    })
    return actions;
  };

  function handleCreate() {
    openConnectionDrawer(true, {
      isUpdate: false,
    });
  }

  function showPartnerDetail(record: Recordable) {
    openPartnerDetailDrawer(true, {
      record,
    });
  }

  function viewCertificate(record: Recordable) {
    openCertificateDetailDrawer(true, {
      record,
    });
  }

  async function handleCancel(record: Recordable) {
    const params: UpdateConnectionStateParams = {
      state: connectionStateEnum.CANCELLED,
    }
    await changeConnectionState(record.id, params);
    reload();
  }

  function generateCertificate(record: Recordable) {
    openCertificateDrawer(true, {
      record,
    });
  }

  function downloadCertificate(record: Recordable) {
    downloadByUrl({
      url: record.our_side_certificate.url,
      target: '_self',
    });
  }

  function handleSuccess() {
    reload();
  }

  function onFetchSuccess() {
    if (!!ifOpenCertificate.value) {
      nextTick(firstOpenGenerateCertificate);
    }
  }

  function firstOpenGenerateCertificate() {
    ifOpenCertificate.value = false;
    const tableAction = unref(tableRef);
    const record = tableAction?.getDataSource()[0];
    openCertificateDrawer(true, {
      record,
    });
  }

</script>